import Vue from 'vue'
import Router from 'vue-router'
import store from '@/vuex/store'
import {postRequest, uploadFileRequest, getRequest, deleteRequest, putRequest} from '../axios/api'
import Pub from '../assets/utils'

// 挂在postRequest,getRequest,deleteRequest到vue的原型中
Vue.prototype.postRequest = postRequest
Vue.prototype.uploadFileRequest = uploadFileRequest
Vue.prototype.getRequest = getRequest
Vue.prototype.deleteRequest = deleteRequest
Vue.prototype.putRequest = putRequest
Vue.prototype.Pub = Pub

Vue.use(Router)

let router = new Router({
  routes: [
    {
      path: '/layout',
      component: (resolve) => require(['@/components/layout.vue'], resolve),
      children: []
    },
    {
      path: '/',
      redirect: '/layout'
    },
    {
      path: '/login',
      // name: 'login',
      meta: {requireAuth: false},
      component: (resolve) => require(['@/components/login.vue'], resolve)
    },
    {
      path: '/404',
      component: (resolve) => require(['@/components/404.vue'], resolve),
      // name: '',
      hidden: true
    },
    {
      path: '/500',
      component: (resolve) => require(['@/components/500.vue'], resolve),
      // name: '',
      hidden: true
    }
  ]
})

// 处理页面刷新后菜单数据丢失问题
let list = JSON.parse(sessionStorage.getItem('menList'))
if (list && list.length > 0) {
  let routes = []
  for (let i = 0; i < list.length; i++) {
    routes.push({
      // name: list[i].name,
      path: list[i].path,
      component: (resolve) => require(['@/' + list[i].url + '.vue'], resolve)
    })
  }
  router.options.routes[0].children = routes
  router.addRoutes(router.options.routes)
}

router.beforeEach((to, from, next) => {
  // 添加浏览器F5监听程序
  window.addEventListener('load', function () {
    next({
      path: '/home'
    })
  })
  // 查看那些路由需要进行登录验证
  if (to.meta.requireAuth === undefined) {
    // 获取token看是否过期
    if (store.state.token) {
      next()
    } else {
      next({
        path: '/login'
      })
    }
  } else {
    next()
  }
})
export default router
